<script setup>
import { ref, onMounted } from 'vue'

const sentence = ref('')
const dateInfo = ref('')

// 获取每日一言数据
const fetchSentence = async () => {
  try {
    // 并行请求数据
    const [sentenceRes] = await Promise.all([
      fetch('/api/blog/sentence'),
    ])

    const sentenceData = await sentenceRes.json()

    if(sentenceData.error) throw sentenceData.error

    sentence.value = sentenceData.sentence

  } catch (error) {
    sentence.value = '数据加载失败，请稍后再试'
    dateInfo.value = '日期获取失败'
  }
}

// 格式化日期
const formatDate = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = now.getMonth() + 1
  const date = now.getDate()
  const week = ['日', '一', '二', '三', '四', '五', '六'][(now.getDay()) % 7] // 调整星期计算
  dateInfo.value = `${year}年${month}月${date}日 星期${week}`
}

// 添加加载动画
const isLoading = ref(true)

onMounted(() => {
  fetchSentence()
  formatDate() // 调用格式化日期函数
  isLoading.value = false
})
</script>

<template>
  <div class="sentence">
    <strong>每日一句</strong>
    <h2>{{ dateInfo }}</h2>
    <p v-if="!isLoading">{{ sentence }}</p>
    <p v-else class="loading">加载中...</p>
  </div>
</template>

<style scoped>
.sentence {
  margin-top: auto;
  margin-bottom: 20px;
  position: relative;
  padding: 30px 10px 0 10px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  border-radius: 4px;
  cursor: default;
  background: var(--card-bg-color, #FFF);
  transition: all 0.3s ease;
  min-height: 100px;
}
.sentence:hover {
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  transform: translateY(-2px);
}
.sentence strong {
  background: var(--sentence-date-color,  #3399CC);
  color: var(--card-text-color, #FFF);
  font-size: 14px;
  font-weight: 100;
  padding: 5px 10px;
  position: absolute;
  left: 0;
  top: 0;
}
.sentence h2 {
  color: var(--sentence-date-color,  #3399CC);
  font-size: 20px;
  margin: 10px 0px;
}
.sentence p {
  margin: 15px 0 0 0;
  font-size: 14px;
  color: var(--card-title-color, #AAA);
}
/* 保留原有样式，新增以下样式 */
.loading {
  animation: blink 1.5s infinite;
}

@keyframes blink {
  0% { opacity: 0.4; }
  50% { opacity: 1; }
  100% { opacity: 0.4; }
}
</style>
